<?php

declare(strict_types=1);

namespace App\Controller\Publics\V2\Orders;

use App\Controller\Publics\V2\Controllers;
use App\Services\Orders\Order;
use App\Utils\Http\Request;
use Hyperf\Collection\Arr;
use Hyperf\Context\ApplicationContext;
use Hyperf\Snowflake\IdGeneratorInterface;
use Psr\Http\Message\ResponseInterface;
use App\Request\Orders\No179 as No179Request;

/**
 * 海关跨境电商进口统一版信息化系统平台数据实时获取接口（试行）
 * @author zx
 * @package App\Controller\Publics\V2\Orders
 */
class Declaration extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = No179Request::class;

    public function __construct(
        Order $orderServices,
        protected Request $http
    )
    {
        parent::__construct();
        $this->services = $orderServices;
    }

    /**
     * 海关 179 号公告获取信息
     * @author zx
     * @return ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Throwable
     */
    public function save():ResponseInterface
    {
        try {
            $input = $this->input(['openReq']);
        } catch (\Throwable $throwable) {
            return respond([], $throwable->getMessage(), '20001', [
                'serviceTime' => time() * 1000
            ]);
        }

        $openReq = json_decode(htmlspecialchars_decode($input['openReq']), true);
        /** @var \App\Model\Orders\Order $orderModel */
        $orderModel = $this->services->where('paid_no', $openReq['orderNo'])->first();
        if (!$orderModel) {
            return respond([], '订单不存在', '20004', [
                'serviceTime' => $openReq['serviceTime']
            ]);
        }

        $params = $orderModel->toNo179Array();
        $params['sessionID'] = $openReq['sessionID'];
        $container = ApplicationContext::getContainer();
        $generator = $container->get(IdGeneratorInterface::class);

        $EData = base64_encode(json_encode([
            'version' => '1.0',
            'commitTime' => date('YmdHis'),
            'cusName' => '上海数析信息技术有限公司',
            'cusCode' => '31119602H4',
            'serialNumber' => $generator->generate(),
            'Token' => 'dI5s8p5Q5I2jxnbY32UxL3SJAcz7bXhV'
        ], JSON_UNESCAPED_UNICODE));
        $payExInfoStr = base64_encode(json_encode($params, JSON_UNESCAPED_UNICODE));

        $response = $this->http->post('https://jk.shcepp.com/cepsi/ceppSignInter', compact('EData', 'payExInfoStr'));
        logs($response);
        if (!$response || !$signArr = json_decode($response, true)) {
            return respond([], '失败', '20000', [
                'serviceTime' => $openReq['serviceTime']
            ]);
        }
        if (Arr::get($signArr, 'status') !== 'success') {
            return respond([], '失败', '20000', [
                'serviceTime' => $openReq['serviceTime']
            ]);
        }
        $params['certNo'] = $signArr['certNo'];
        $params['signValue'] = $signArr['signValue'];
        $params['serviceTime'] = $signArr['serviceTime'];

        $payExInfoStr = json_encode($params, JSON_UNESCAPED_UNICODE);
        $response = $this->http->post('https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload', compact('payExInfoStr'));
        logs($response);
        if (!$response || !$result = json_decode(htmlspecialchars_decode($response), true)) {
            return respond([], '失败', '20000', [
                'serviceTime' => $openReq['serviceTime']
            ]);
        }
        if (Arr::get($result, 'code') !== '10000') {
            return respond([], '失败', '20000', [
                'serviceTime' => $openReq['serviceTime']
            ]);
        }
        return respond([], '成功', '10000', [
            'serviceTime' => $openReq['serviceTime']
        ]);
    }
}
